package com.example.demo.verify;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NoEmptyNoTelphoneValidator implements ConstraintValidator<NoEmptyNoTelphone, Object> {
    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext context) {
        if (obj == null) {
            return false;
        }

        if (obj.toString().trim().isEmpty()) {
            return true;
        }

        Matcher m;
        boolean isPhone;
        Pattern p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的
        Pattern p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的
        if (obj.toString().length() > 9) {
            m = p1.matcher(obj.toString());
            isPhone = m.matches();
        } else {
            m = p2.matcher(obj.toString());
            isPhone = m.matches();
        }
        return isPhone;
    }
}
